package com.yanxu.get;

import com.alibaba.fastjson.JSON;
import com.yanxu.common.SnmpParameter;
import com.yanxu.inter.SnmpRequestHandle;
import org.snmp4j.PDU;
import org.snmp4j.ScopedPDU;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.VariableBinding;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 折戟沉沙铁未销
 * @version V1.0
 * @date 2023/11/9-2023
 * @Description: Snmp get 请求
 */
@Component("snmp-get")
public class SnmpGetRequest extends SnmpRequestHandle {

    /**
     * 发动请求之前
     * 主要是定义 PDU(oid) 等参数对象
     *
     * @param snmpParameter
     * @throws Exception
     */
    @Override
    public List<PDU> beforeRequest(SnmpParameter snmpParameter) throws Exception {
        List<PDU> pduList=new ArrayList<>();
        String[] oids = snmpParameter.getOids();
        for (String singleOid : oids) {
            String[] OIDArray = singleOid.split(":");
            for (String oid : OIDArray) {
                System.out.println(oid);
                PDU pdu = (snmpParameter.getVersion() == SnmpConstants.version3) ? (new ScopedPDU()) : (new PDU());
                pdu.add(new VariableBinding(new OID(singleOid)));
                pdu.setType(PDU.GET);
                pduList.add(pdu);
            }
        }
        return pduList;
    }

    /**
     * 处理请求之后的结果
     */
    @Override
    public void handleResult(List<Object> resultList) {
        for (Object requestResult : resultList) {
            Map<String, List<String>> oidResultValueMaps = new HashMap<>();
            List<? extends VariableBinding> variableBindings = (List<? extends VariableBinding>) requestResult;
            for (VariableBinding variableBinding : variableBindings) {
                String snmpReturnoid = variableBinding.getOid().toString();
                if(oidResultValueMaps.containsKey(snmpReturnoid)){
                    oidResultValueMaps.get(snmpReturnoid).add(variableBinding.getVariable().toString());
                }else{
                    List<String> varValues = new ArrayList<>();
                    varValues.add(variableBinding.getVariable().toString());
                    oidResultValueMaps.put(snmpReturnoid,varValues);
                }
            }
            String jsonResult = JSON.toJSONString(oidResultValueMaps);
            System.out.println(jsonResult);
        }
    }

}